package com.xxkk.mvc.control;

//import gmPayServer.GMPayServer;

import com.alibaba.fastjson.JSONObject;
import com.xxkk.gameCore.net.sql.mapper.UserInfoMapper;
import com.xxkk.gameCore.net.sql.pojo.UserInfo;
import com.xxkk.mvc.service.SqlService;
import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

@Controller
@RequestMapping(value = "/pay")
public class ControlDemo {

    @Autowired
    private SqlService sqlService;

    private static final Logger logger = Logger.getLogger(ControlDemo.class);

    private final long twepoch = 1288834974657L;
    private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private final long sequenceBits = 12L;
    private final long workerIdShift = sequenceBits;
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long workerId = 1;
    private long datacenterId = 1;
    private long sequence = 0L;
    private long lastTimestamp = -1L;


    public synchronized long nextId() {
        long timestamp = timeGen();
        logger.info("订单时间戳:" + timestamp);
        if (timestamp < lastTimestamp) {
            //服务器时钟被调整了,ID生成器停止服务.
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    private AtomicLong inc = new AtomicLong();
    @Autowired
    private UserInfoMapper mapper;

    public void sqlTest() {
        SQL sql = new SQL();
        sql.UPDATE("table").SET("amount = amount -100");
    }

    @RequestMapping("/mt")
    @ResponseBody
    public String mapperTest(@RequestBody Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        JSONObject obj = new JSONObject(paramMap);
//        int res = mapper.delByIdAndAccount(obj.getIntValue("id"), obj.getString("account"));
//        List<UserInfo> res = mapper.selectTest(obj.getString("name"));
        Object _1 = obj.get("1");
        Object _2 = obj.get("2");
        UserInfo res = mapper.selectByLimit((int) _1, (int) _2);
        return JSONObject.toJSONString(res);
    }

    @RequestMapping("/orderId")
    @ResponseBody
    public String generatorId(HttpServletRequest request, HttpServletResponse response) {//@RequestBody Map<String, Object> paramMap,
        long id = this.nextId();
        logger.info("生成订单号请求 生成id：" + id); //+" 收到参数:" + paramMap.toString());
        String res = Long.toString(id);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        logger.info("res：" + res + " lenth:" + res.length());
        return uuid + this.inc.getAndIncrement() + res;
    }

    @RequestMapping("/order")
    @ResponseBody
    public String order(HttpServletRequest request, HttpServletResponse response) {//@RequestBody Map<String, Object> paramMap,
        //下单请求
        //打印请求参数
        //生成订单 订单号。。。
        //生成验签
        //发送请求
        //请求异常处理
        //响应结果
        return "";
    }

    @RequestMapping("/orderCallBack")
    @ResponseBody    //下单回调接口
    public String orderCallBack(HttpServletRequest request, HttpServletResponse response) {
        //验证回调
        //处理回调
        //发放奖励
        return "";
    }

//    @ResponseBody
//    @RequestMapping("/p1")
//    public String commPayCtrl(@RequestBody Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
//
//        System.out.println("[ControlDemo] 发送请求代收下单：" + paramMap.toString());
//        JSONObject jsonObject = JSONObject.fromObject(paramMap);
//        // 做点什么
////        String res = GMPayServer.Instance().commPay(jsonObject);
//        return "index";//JSONObject.fromObject(res);
//    }
//    @RequestMapping("/sign")
//    @ResponseBody
//    public String sign(@RequestBody Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
//        System.out.println("签名参数：" + paramMap.toString());
//        String key = (String) paramMap.get("key");
//        paramMap.remove("key");
//        paramMap.remove("sign");
//        JSONObject jsonObject = JSONObject.fromObject(paramMap);
////        String key = "5cde8dfe0c894429bb6b86ec05f8406f";//"7bd9c036109b4cab80f3c9ee225e2b70"; //密钥
//        try {
//            String signstr = SignTool.md5Sign(jsonObject, key);//签名方法
//            return signstr;
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }

//    @ResponseBody
//    @RequestMapping("/p2")
//    public String sqlDemo(Model model) {
//        //GMPayServer.Instance().commPay("");
//        try {
//            logger.info("#xxkk1");
//            UserInfo userInfo = sqlService.getUserInfoById(2);
//            System.out.println("xxkk#xxkk");
//            logger.info(userInfo.toString());
//            return userInfo.toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "index";
//    }

//    @RequestMapping("/list")
//    public String greeting() {
//        return "index";
//    }

//    @RequestMapping("/index")
//    public String index() {
////        logger.info("登陆首页");
//        return "web/index";
//    }

//    @RequestMapping(value = "login")
//    @ResponseBody
//    public String login(HttpServletRequest request, HttpServletResponse response,
//                        String account, String password) throws Exception {
////        logger.info("登陆");
//        String param = "false";
//        if ("admin".equals(account) && "111111".equals(password)) {
//            param = "true";
//        }
//        return param;
//    }

//    @RequestMapping(value = "main")
//    public String main(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
//        model.addAttribute("ip", "192.168.1.66");
//        model.addAttribute("address", "青岛");
////        model.addAttribute("time", DateUtil.getTime());
//        return "web/main";
//    }

}
